package repman;

import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class RepTreeModel implements TreeModel
{ 
   private Document doc;
   private XPath xPath;
/**
      Constructs a document tree model.
      @param doc the document
   */
   public RepTreeModel(Document doc) { 
	   this.doc = doc;
	   xPath =  XPathFactory.newInstance().newXPath();
   }

   public Object getRoot() { 
   try {
		return (Node) xPath.compile("/reports/directory").evaluate(doc, XPathConstants.NODE);
	} catch (XPathExpressionException e) {
		return null;
	}
   }

   public int getChildCount(Object parent)
   {  
    Node node = (Node) parent;
    NodeList list;
	try {
		list = (NodeList) xPath.compile("group | report").evaluate(parent, XPathConstants.NODESET);
		return list.getLength();
	} catch (XPathExpressionException e) {
		return 0;	
	}
   }

   public Object getChild(Object parent, int index)
   {  
      Node node = (Node) parent;
      NodeList list;
	try {
		list = (NodeList) xPath.compile("group | report").evaluate(parent, XPathConstants.NODESET);
	     return list.item(index);
	} catch (XPathExpressionException e) {
		return null;
	}
   }

   public int getIndexOfChild(Object parent, Object child)
   {  
      Node node = (Node) parent;
      NodeList list = node.getChildNodes();
      for (int i = 0; i < list.getLength(); i++)
         if (getChild(node, i) == child)
            return i;
      return -1;
   }

   public boolean isLeaf(Object node) { return getChildCount(node) == 0; }
   public void valueForPathChanged(TreePath path, Object newValue) {}
   public void addTreeModelListener(TreeModelListener l) {}
   public void removeTreeModelListener(TreeModelListener l) {}
}